package com.example.myapplication;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.graphics.Rect;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class MyAccessibilityService extends AccessibilityService {

    private static MyAccessibilityService instance;

    @Override
    public void onServiceConnected() {
        super.onServiceConnected();
        instance = this;

        Toast.makeText(this, "无障碍服务已启动", Toast.LENGTH_SHORT).show();

        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        info.notificationTimeout = 100;
        info.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
        info.flags |= AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS;

        setServiceInfo(info);
    }

    public static MyAccessibilityService getInstance() {
        return instance;
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED ||
                event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            Log.d("MyAccessibilityService", "窗口发生变化，尝试获取 UI 结构");
//            getAllWindowsUiJson(); // 可根据需求发送到服务器
        }
    }

    @Override
    public void onInterrupt() {
        Toast.makeText(this, "无障碍服务被中断", Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取当前所有窗口的 UI 结构
     */
    public JSONObject getAllWindowsUiJson() throws JSONException {
        List<AccessibilityWindowInfo> windows = getWindows();
        if (windows == null || windows.isEmpty()) {
            JSONObject errorJson = new JSONObject();
            try {
                errorJson.put("error", "未找到窗口");
            } catch (Exception e) {
                Log.d("TAG", String.valueOf(e));
            }
            return errorJson;
        }


        try {
            JSONArray windowsArray = new JSONArray();
            for (AccessibilityWindowInfo window : windows) {
                AccessibilityNodeInfo rootNode = window.getRoot();
                if (rootNode != null) {
                    JSONObject windowJson = new JSONObject();
                    windowJson.put("type", window.getType());
                    windowJson.put("nodes", serializeNode(rootNode));
                    windowsArray.put(windowJson);
                }
            }

            JSONObject result = new JSONObject();
            result.put("windows", windowsArray);
            return result;
        } catch (Exception e) {
            Log.e("MyAccessibilityService", "转换 UI 结构失败", e);
            return new JSONObject().put("error", "未找到窗口");
        }
    }

    /**
     * 递归序列化节点
     */
    private JSONObject serializeNode(AccessibilityNodeInfo node) throws Exception {
        if (node == null) return null;

        JSONObject nodeJson = new JSONObject();

        nodeJson.put("text", node.getText() != null ? node.getText().toString() : "");
        nodeJson.put("className", node.getClassName() != null ? node.getClassName().toString() : "");
        nodeJson.put("packageName", node.getPackageName() != null ? node.getPackageName().toString() : "");
        nodeJson.put("contentDescription", node.getContentDescription() != null ? node.getContentDescription().toString() : "");
        nodeJson.put("hint", node.getHintText() != null ? node.getHintText().toString() : "");
        nodeJson.put("viewIdResourceName", node.getViewIdResourceName() != null ? node.getViewIdResourceName() : "");

        nodeJson.put("clickable", node.isClickable());
        nodeJson.put("enabled", node.isEnabled());
        nodeJson.put("focusable", node.isFocusable());
        nodeJson.put("focused", node.isFocused());
        nodeJson.put("scrollable", node.isScrollable());
        nodeJson.put("longClickable", node.isLongClickable());
        nodeJson.put("selected", node.isSelected());
        nodeJson.put("password", node.isPassword());
        nodeJson.put("checkable", node.isCheckable());
        nodeJson.put("checked", node.isChecked());
        nodeJson.put("dismissible", node.isDismissable());
        nodeJson.put("editable", node.isEditable());
        nodeJson.put("importantForAccessibility", node.isImportantForAccessibility());
        nodeJson.put("visibleToUser", node.isVisibleToUser());

        Rect bounds = new Rect();
        node.getBoundsInScreen(bounds);
        nodeJson.put("boundsInScreen", bounds.toShortString());
        node.getBoundsInParent(bounds);
        nodeJson.put("boundsInParent", bounds.toShortString());

        // 子节点
        JSONArray childrenArray = new JSONArray();
        for (int i = 0; i < node.getChildCount(); i++) {
            JSONObject childJson = serializeNode(node.getChild(i));
            if (childJson != null) childrenArray.put(childJson);
        }
        nodeJson.put("children", childrenArray);

        // 动作
        JSONArray actionsArray = new JSONArray();
        List<AccessibilityNodeInfo.AccessibilityAction> actionList = node.getActionList();
        if (actionList != null) {
            for (AccessibilityNodeInfo.AccessibilityAction action : actionList) {
                actionsArray.put(action.getId());
            }
        }
        nodeJson.put("actions", actionsArray);

        // text selection
        nodeJson.put("textSelectionStart", node.getTextSelectionStart());
        nodeJson.put("textSelectionEnd", node.getTextSelectionEnd());

        return nodeJson;
    }
}
